using System;
using System.Collections.Generic;
using UnityEngine;
using Framework;
using Object = UnityEngine.Object;

namespace GameCore
{
    public class PrefabFactory : MonoSingleton<PrefabFactory>
    {
        private readonly Dictionary<Type, Dictionary<ResourceID, object>> prefabs = new();

        public static void AddPrefab<T>(ResourceID resourceID, T prefab) where T : Object
        {
            if (!Instance.prefabs.TryGetValue(typeof(T), out Dictionary<ResourceID, object> dict))
                Instance.prefabs.Add(typeof(T), dict = new Dictionary<ResourceID, object>());
            dict[resourceID] = prefab;
        }

        public static T GetPrefab<T>(ResourceID resourceID) where T : Object
        {
            if (!Instance.prefabs.TryGetValue(typeof(T), out Dictionary<ResourceID, object> dict)) return null;
            return dict.GetValueOrDefault(resourceID, null) as T;
        }

        public static T CreateInstance<T>(ResourceID resourceID) where T : Object
        {
            if (!Instance.prefabs.TryGetValue(typeof(T), out Dictionary<ResourceID, object> dict)) return null;
            return Instantiate(dict.GetValueOrDefault(resourceID, null) as T);
        }
    }
}